package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wisdge.dataservice.Result;
import cn.com.elite.Util;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;

/**
 *
 * @Title: autoDECaseReqDate
 * @Description1: DE30011 市平台市属责任单位申请延期 市平台市属责任单位申请延期
 * @Description2: DE30012 市属责任单位案件延期审核结果查询 市属责任单位案件处置申请延期审核结果同步
 * @author: LiJuntao
 * @date 2020-05-15 下午1:16:44
 *
 */
public class autoDECaseReqDate implements CallBackInvoke {
    private int i
    private static final Log log = LogFactory.getLog(autoDECaseReqDate.class);

    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String paramString) {

        String logPrefix = "autoDECaseReqDate 申请延期&审核结果查询-";

        long rstartTime = System.currentTimeMillis();
        boolean CaseReqDate = getCaseReqDate(eliteBean);
        log.debug(logPrefix + "申请延期-结束(" + CaseReqDate + ")...开始时间:" + rstartTime + " 处理时长(毫秒):" + (System.currentTimeMillis() - rstartTime));

        rstartTime = System.currentTimeMillis();
        boolean CaseReqDateResult = getCaseReqDateResult(eliteBean);
        log.debug(logPrefix + "审核结果查询-结束(" + CaseReqDateResult + ")...开始时间:" + rstartTime + " 处理时长(毫秒):" + (System.currentTimeMillis() - rstartTime));
    }


    public static boolean getCaseReqDate(EliteBean eliteBean) {

        String logPrefix = "DE30011 市平台市属责任单位申请延期-";

        //初始化执行耗时信息
        long rstartTime = System.currentTimeMillis();
        long rendTime = System.currentTimeMillis();
        log.debug(logPrefix + "开始...时间:" + rstartTime);

        //初始化同步结果
        String errorCode = "";
        String errorMsg = "";
        int syncFlag = 0;

        //查询待同步数字化城管的反馈结果案件
        String syncTaskSQL = "select rec_Id,evtId,newLimit,reqDate,reqUserName,reqUserDeptName,reqReason,activityInstId,params from SZWG_DE_Case_ReqDate where syncFlag = 0 and createTime > DATEADD(day, -7, GETDATE()) and syncTimes < syncLimit";
        List syncTaskList = eliteBean.chaxun_sql(syncTaskSQL, "dataSource");
        log.debug(logPrefix + "获取数据SQL:" + syncTaskSQL + " 数量:" + syncTaskList.size());

        if (syncTaskList.size() > 0) {
            for (int i = 0; i < syncTaskList.size(); i++) {

                String requestId = "SW-" + KHUtil.getRandomString(29).toUpperCase();
                String time = String.valueOf(System.currentTimeMillis());

                // 设置头文件
                Map<String, String> headMap = new HashMap<String, String>();
                headMap.put("Content-Type", "application/json");
                headMap.put("funCode", "DE30011");
                headMap.put("appId", getProperty.get("DE.appId"));
                headMap.put("appKey", getProperty.get("DE.appKey"));
                headMap.put("requestId", requestId);
                headMap.put("timestamp", time);
                headMap.put("encoding", "");

                String attachListSQL = "select attachType, attachFilePath, attachFileName from SZWG_DE_Case_ReqAttachs where attachStatus = 0 and rec_Id = '" + syncTaskList.get(i).get("rec_Id") + "'"
                List<Map<String, Object>> getAttachList = eliteBean.chaxun_sql(attachListSQL, "dataSource");
                log.debug(logPrefix + "getAttachListSQL获取数据结果:" + getAttachList + " 数量:" + getAttachList.size());

                //定义附件对象
                JSONArray callArray = new JSONArray();
                for (int j = 0; j < getAttachList.size(); j++) {
                    JSONObject attachListJson = new JSONObject();
                    Map<String, Object> reMap = getAttachList.get(j);

                    String attachType = reMap.get("attachType").toString();
                    String attachFilePath = reMap.get("attachFilePath").toString();
                    String attachFileName = reMap.get("attachFileName").toString();

                    attachListJson.put("attachType", attachType);
                    attachListJson.put("attachFilePath", attachFilePath);
                    attachListJson.put("attachFileName", attachFileName);

                    callArray.put(attachListJson);
                }


                //定义调用报文
                JSONObject callJson = new JSONObject();
                callJson.put("evtId", syncTaskList.get(i).get("evtId"));
                callJson.put("newLimit", syncTaskList.get(i).get("newLimit"));
                callJson.put("reqDate", syncTaskList.get(i).get("reqDate"));
                callJson.put("reqUserName", syncTaskList.get(i).get("reqUserName"));
                callJson.put("reqUserDeptName", syncTaskList.get(i).get("reqUserDeptName"));
                callJson.put("reqReason", syncTaskList.get(i).get("reqReason"));
                callJson.put("activityInstId", syncTaskList.get(i).get("activityInstId"));
                callJson.put("params", syncTaskList.get(i).get("params"));
                callJson.put("umEvtAttachList", callArray);

                //调用数字化城管接口
                try {
                    log.debug(logPrefix + "调用地址URL：" + getProperty.get("DE.URL") + "调用发送报文信息：" + callJson.toString());
                    String reJson = Util.doHttpPostUseHead(getProperty.get("DE.URL"), callJson.toString(), "UTF-8", 10000, 0, headMap);
                    log.debug(logPrefix + "调用返回信息：" + reJson);

                    JSONObject inObject = new JSONObject(reJson);
                    errorCode = KHUtil.GetJV(inObject, "errorCode");
                    errorMsg = KHUtil.GetJV(inObject, "errorMsg");
                    log.debug(logPrefix + "解析返回信息errorCode：" + errorCode);
                    log.debug(logPrefix + "解析返回信息errorMsg：" + errorMsg);
                    syncFlag = 1;
                } catch (Exception e) {
                    log.error(logPrefix + "调用数字化城管接口错误:" + e.getMessage());
                    errorCode = "";
                    syncFlag = 0;
                }

                def updateCaseReqComSQL1 = eliteBean.update("Update SZWG_DE_Case_ReqDate Set syncFlag = '" + syncFlag + "', syncLastTime = getdate(),syncTimes = syncTimes + 1 WHERE rec_Id = '" + syncTaskList.get(i).get("rec_Id") + "'", "dataSource");
                log.debug(logPrefix + "SQL更新数据(将调用次数累加):" + updateCaseReqComSQL1);

                //为避免对方失败返回信息异常导致插入失败所以与次数更新分开
                def updateCaseReqComSQL2 = eliteBean.update("Update SZWG_DE_Case_ReqDate Set errorCode = '" + errorCode + "',errorMsg = '" + errorMsg + "' WHERE rec_Id = '" + syncTaskList.get(i).get("rec_Id") + "'", "dataSource");
                log.debug(logPrefix + "SQL更新数据(记录调用结果):" + updateCaseReqComSQL2);
            }

            rendTime = System.currentTimeMillis();
            log.debug(logPrefix + "结束..." + " 处理时长(毫秒):" + (rendTime - rstartTime));

        } else {
            rendTime = System.currentTimeMillis();
            log.debug(logPrefix + "无任务-结束..." + " 处理时长(毫秒):" + (rendTime - rstartTime));
        }

    }

    // DE30012 市属责任单位案件延期审核结果查询 市属责任单位案件处置申请延期审核结果同步
    public static boolean getCaseReqDateResult(EliteBean eliteBean) {

        String logPrefix = "DE30012 市属责任单位案件延期审核结果查询-";

        String syncTaskSQL = "select Top 100 r1.evtId from SZWG_DE_Case_ReqDate r1 left join SZWG_DE_Case_ReqDate_Result r2 on r1.evtId = r2.evtId and r1.params = r2.params where r1.syncFlag = 1 and r1.createTime > DATEADD(day, -60, GETDATE()) and r2.rec_Id is null and r1.errorCode = 0 and activityInstId not in (SELECT activityInstId FROM SZWG_DE_Case_ReqComplete where errorCode = 0)and activityInstId not in (SELECT activityInstId FROM SZWG_DE_Case_ReqReturn where errorCode = 0) Order By r1.lastGetResultTime";
        List<Map<String, Object>> syncTaskList = eliteBean.chaxun_sql(syncTaskSQL, "dataSource");
        log.debug(logPrefix + "获取数据SQL:" + syncTaskList.toString() + " 数量:" + syncTaskList.size());

        if (syncTaskList.size() > 0) {
            //拼接请求数组
            JSONArray callArray = new JSONArray();
            ArrayList<String> arrayList = new ArrayList<String>();
            for (int i = 0; i < syncTaskList.size(); i++) {
                Map<String, Object> reMap = syncTaskList.get(i);
                String reevtId = reMap.get("evtId").toString();
                callArray.put(reevtId);

            }
            log.debug(logPrefix + "拼接请求数组:" + callArray);

            String requestId = "SW-" + KHUtil.getRandomString(29).toUpperCase();
            String time = String.valueOf(System.currentTimeMillis());

            //设置头文件
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/json");
            headMap.put("funCode", "DE30012");
            headMap.put("appId", getProperty.get("DE.appId"));
            headMap.put("appKey", getProperty.get("DE.appKey"));
            headMap.put("requestId", requestId);
            headMap.put("timestamp", time);
            headMap.put("encoding", "");

            //String callJson = "{\"evtIds\":" + callArray.toString() + "}";
            JSONObject callJson = new JSONObject();
            callJson.put("evtIds", callArray);

            log.debug(logPrefix + "调用地址URL：" + getProperty.get("DE.URL") + "调用发送报文信息：" + callJson.toString());
            String reJson = Util.doHttpPostUseHead(getProperty.get("DE.URL"), callJson.toString(), "UTF-8", 10000, 0, headMap);
            log.debug(logPrefix + "调用返回信息：" + reJson);

            JSONObject inObject = new JSONObject(reJson);
            String errorCode = KHUtil.GetJV(inObject, "errorCode");
            String errorMsg = KHUtil.GetJV(inObject, "errorMsg");
            String data = KHUtil.GetJV(inObject, "data");

            if (errorCode.equals("0")) {

                long rstartTime = System.currentTimeMillis();
                long rendTime = System.currentTimeMillis();
                log.debug(logPrefix + "处理开始时间:" + rstartTime);

                try {
                    JSONArray arrJsonArray = new JSONArray(data);

                    int arrInt = arrJsonArray.length();
                    log.debug(logPrefix + "接入List数量:" + arrInt);

                    for (int i = 0; i < arrInt; i++) {

                        JSONObject arrCustJson = arrJsonArray.getJSONObject(i);

                        //工单状态信息
                        String evtId = KHUtil.GetJV(arrCustJson, "evtId");
                        String auditDate = KHUtil.GetJV(arrCustJson, "auditDate");
                        String auditUserName = KHUtil.GetJV(arrCustJson, "auditUserName");
                        String auditType = KHUtil.GetJV(arrCustJson, "auditType");
                        String auditOpinion = KHUtil.GetJV(arrCustJson, "auditOpinion");
                        String isPass = KHUtil.GetJV(arrCustJson, "isPass");
                        String oldLimit = KHUtil.GetJV(arrCustJson, "oldLimit");
                        String selfDefLimit = KHUtil.GetJV(arrCustJson, "selfDefLimit");
                        String params = KHUtil.GetJV(arrCustJson, "params");


                        def updateCaseReqComSQL1 = eliteBean.update("Update SZWG_DE_Case_ReqDate Set lastGetResultTime = getdate() WHERE params = '" + params + "'", "dataSource");
                        log.debug(logPrefix + "SQL更新数据最后一次获取结果的时间:" + updateCaseReqComSQL1);

                        //查询现有当前工单编号是否存在现有工单
                        def getSelectSQL = eliteBean.chaxun_sql("SELECT rec_Id from SZWG_DE_Case_ReqDate_Result where evtId = '" + evtId + "'", "dataSource");
                        log.debug(logPrefix + "查询审核结果是否已经存在 SQL:" + getSelectSQL + " 结果数量:" + getSelectSQL.size());

                        if (getSelectSQL.size() >= 0) {
                            // 插入数据
                            String[] batchSQL = new String[1];
                            batchSQL[0] = "INSERT INTO SZWG_DE_Case_ReqDate_Result (rec_Id, evtId, auditDate, auditUserName, auditType, auditOpinion, isPass, oldLimit, selfDefLimit, params, createTime) VALUES (NEWID(), '" + evtId + "', '" + auditDate + "', '" + auditUserName + "', '" + auditType + "', '" + auditOpinion + "', '" + isPass + "', '" + oldLimit + "', '" + selfDefLimit + "', '" + params + "', GETDATE());";

                            log.debug(logPrefix + "当前审核结果不存在新建结果SQL:" + batchSQL.toString());
                            def dataresult = eliteBean.updateBatch(batchSQL, "dataSource");
                            log.debug(logPrefix + "当前审核结果不存在新建结果SQL结果:" + dataresult.toString());
                        }
                    }

                    //生成处理完成时间
                    rendTime = System.currentTimeMillis();

                    // 包装拼接返回JSONObject
                    log.debug(logPrefix + "处理完成、审核结果处理时长(毫秒):" + (rendTime - rstartTime));

                } catch (JSONException e) {
                    rendTime = System.currentTimeMillis();
                    log.error(logPrefix + "处理失败(" + e.getMessage() + "),审核结果处理时长(毫秒):" + (rendTime - rstartTime));
                }
            }
        } else {
            log.debug(logPrefix + "处理完成、无待查询审核结果案件...");
        }

    }
}